var combinationSum = function (candidates, target) {
  let len = candidates.length;
  let ans = [];
  candidates.sort((a, b) => a - b);
  const dfs = (residue, begin, path, ans) => {
    if (residue === 0) {
      ans.push(path);
      return;
    }
    for (let i = begin; i < len; i++) {
      if (residue - candidates[i] < 0) break;
      path.push(candidates[i]);
      // path.slice 拷贝数组，防止改变原数组
      dfs(residue - candidates[i], i, path.slice(), ans);
      // 回溯，每次删掉末尾的那个，再进入下次循环
      path.pop();
    }
  }
  dfs(target, 0, [], ans);
  return ans;
};

